/** 1. 站点类目提取脚本 */
<template>
  <div class="editor_container">
    <div class="code-container">
      <div class="script-header">
        <a-button type="primary" :loading="updateLoading" @click="save_script"
          >更新脚本</a-button
        >
      </div>
      <MonacoEditor
        editorId="siteCategoryEditor"
        v-model="script_code"
        lang="python"
      />
    </div>
    <div class="result-container">
      <div class="result-header">
        <h4>执行结果</h4>
        <div class="result-header-end">
          <!-- <a-button v-show="current_site" @click="save_script">
            <RocketOutlined />
            保存脚本
          </a-button> -->
          <a-button v-show="current_site" @click="execute_result">
            <RocketOutlined />
            解析执行结果
          </a-button>
          <a-button type="primary" :disabled="!current_site" @click="execute">
            <RocketOutlined />
            {{ current_site ? '执行' : '请选择站点' }}
          </a-button>
        </div>
      </div>
      <div class="script-body">
        <MonacoEditor
          editorId="siteCategoryResultEditor"
          v-model="result_code"
          lang="json"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { script_execute } from '@/api/script';
import { message } from 'ant-design-vue';
import {
  get_site_script_data,
  update_site_script_data,
} from '@/utils/storage.js';

const props = defineProps({
  current_site: {
    type: String,
    default: '',
  },
  tab_data: {
    type: Object,
    default: () => {},
  },
});

const emit = defineEmits(['switch_tab']);

// 脚本 id
const script_id = ref(-1);
// 脚本内容
const script_code = ref('# 请从左侧的站点列表选择需要处理的站点');
// 脚本执行结果
const result_code = ref('[\n  { "value": "1", "label": "类目1" }\n]');
const updateLoading = ref(false);

// 解析执行结果
const execute_result = () => {
  let category_list = JSON.parse(result_code.value).category_list;
  localStorage.setItem(
    `${props.current_site}-siteCategoryResult`,
    JSON.stringify(category_list, null, 2)
  );
  emit('switch_tab', 'conditionScript');
};

// 执行脚本
const execute = async () => {
  if (script_id.value === -1) {
    message.error('获取脚本信息失败，请手动保存修改后的脚本再刷新页面重试');
    return;
  }
  try {
    let res = await script_execute(script_id.value, [
      {
        dataType: 'string',
        name: 'website_code',
        paramId: '',
        paramType: 1,
        value: props.current_site,
      },
    ]);
    let format_result = JSON.stringify(JSON.parse(res.data), null, 2);
    result_code.value = format_result;
  } catch (err) {
    message.error('执行脚本时发生错误');
    console.error('execute script error ->', err);
  }
};

// 保存脚本
const save_script = async () => {
  // 获取当前脚本
  let script = (await get_site_script_data(props.current_site))?.scripts?.find(
    item => item.description === 'CATEGORY_EXTRACT'
  );
  if (script) {
    script.content = script_code.value;
    updateLoading.value = true;
    // 更新脚本
    await update_site_script_data(props.current_site, script);
    message.success('保存脚本成功');
    updateLoading.value = false;
  } else {
    message.error('获取脚本信息失败，请手动保存修改后的脚本再刷新页面重试');
  }
};

// 页面内容重载
const reload = async () => {
  if (!props.current_site) {
    return;
  }
  // 读取上次脚本运行结果
  let category_result = localStorage.getItem(
    `${props.current_site}-siteCategoryResult`
  );
  if (category_result) {
    result_code.value = category_result;
  } else {
    result_code.value = '';
  }
  // 获取当前脚本
  let script = (await get_site_script_data(props.current_site))?.scripts?.find(
    item => item.description === 'CATEGORY_EXTRACT'
  );
  if (script) {
    script_id.value = script.id;
    script_code.value = script.content;
  } else {
    script_id.value = -1;
    script_code.value = '# 请从左侧的站点列表选择需要处理的站点';
    message.error('获取脚本信息失败，请手动保存修改后的脚本再刷新页面重试');
  }
};

onMounted(async () => {
  await reload();
});

defineExpose({
  reload,
});
</script>

<script>
import MonacoEditor from '@/components/commons/MonacoEditor.vue';
import { Button } from 'ant-design-vue';
import { RocketOutlined } from '@ant-design/icons-vue';

export default {
  name: 'SetCategoryScript',
  components: {
    MonacoEditor,
    AButton: Button,
    RocketOutlined,
  },
};
</script>

<style lang="scss" scoped>
.editor_container {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: flex-start;

  .code-container {
    height: 100%;
    width: 52%;
    display: flex;
    flex-direction: column;
  }

  .script-header {
    height: 50px;
    display: flex;
    align-items: center;
  }

  .script-body {
    flex: 1;
    width: 100%;
    min-height: 0;
  }

  .result-container {
    width: 46%;
    height: 100%;
    display: flex;
    flex-direction: column;

    .result-header {
      height: 50px;
      display: flex;
      flex-direction: row;
      justify-content: space-between;
      align-items: center;
      border-bottom: 1px solid #e8e8e8;
    }
  }
}
</style>
